//
//  AppDelegate.m
//  wobingwoyi
//
//  Created by WGP on 16/7/18.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "AppDelegate.h"
#import "WPTabBarController.h"
#import "WPNewFeatureCollectionVC.h"
#import "WPRegisterViewController.h"
#import "WPReadingInvidialRanking.h"
#import "WPHomeNavigationController.h"
#import "JPUSHService.h"
#import "WPInfomationModel.h"
#import "EBForeNotification.h"
#import "WPMineInforamationVC.h"
#import "WPMineInfomationNVC.h"
#import <Bugly/Bugly.h>
#import "WPHomeViewController.h"
#import "WPCredentialsEditeVC.h"
#import <IQKeyboardManager/IQKeyboardManager.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"
//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"

#define kUMMobClickAppkey @"586f594ff5ade40510000f81"
#define kJPUSHAPPKey @"e28dfcc67ef2749433d879d1"
#define kChannel  @"AppStore"
#define kIsProduction  NO
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

@interface AppDelegate ()

@property(nonatomic,strong)UIView *launchView;
@property (strong, nonatomic) UIImageView *splashView;
@property(nonatomic,strong)UIImageView *bgImageView;

@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
//    开启网络监听
    [GLobalRealReachability startNotifier];
    
    [self prepareKeyboardManager];
    
    
    //UM统计的version标识
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    //友盟应用统计
    UMConfigInstance.appKey = kUMMobClickAppkey;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    //使用集成测试服务
    [MobClick setLogEnabled:NO];
    
    
//    集成mob的shareSDK
    [self shareSDKIntegration];
    
//    集成崩溃统计
    [Bugly startWithAppId:@"a64dc04db9"];
    
    //极光推送Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        //       categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound |UIUserNotificationTypeAlert) categories:nil];
    }
    else
    {
        //categories    nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
    }
    
    //  channel 应用是从哪个渠道下载的（Android有用）
    //  isProduction: 是不是生产环境（发布环境）,如果是NO就是开发环境，如果是YES就是发布环境（生产环境）
    [JPUSHService setupWithOption:launchOptions appKey:kJPUSHAPPKey
                          channel:kChannel
                 apsForProduction:kIsProduction];
    
    //    监听自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
//    默默登陆一次
//    [[WPNetWorkManager sharedNetWorkManager] userLogin];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    self.window.rootViewController = [self defaultViewController];
    
    [self.window makeKeyAndVisible];

    [self launchAnimation];
    
    return YES;
}

#pragma mark - 进入程序设置默认的控制器
-(UIViewController *)defaultViewController
{
    if ([self isNewVersion]) {
        
        return [WPNewFeatureCollectionVC newFeatureCollectionVC];
    }
    return [[WPTabBarController alloc] init];
}

#pragma mark - 是否新版本
-(BOOL)isNewVersion
{
//    1.获得当前版本
    NSString *currentVersion = (NSString *)[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
//    2.获得上一次版本
    NSString *sandBoxKey = @"sandboxKey";
    NSString *sandBoxVersion = [USER_DEFAULTS stringForKey:sandBoxKey];
    
//    3.对比
    BOOL isNewVersion = ![currentVersion isEqualToString:sandBoxVersion];
    
//    4.是新版本,保存新的版本号
    if (isNewVersion) {
        
        [USER_DEFAULTS setObject:currentVersion forKey:sandBoxKey];
        [USER_DEFAULTS synchronize];
    }
    
    return isNewVersion;
}

#pragma mark - 切换控制器的统一方法
-(void)switchController:(UIViewController *)vc
{
    self.window.rootViewController = vc;
}

-(UIImage *)selectedImageByDevice
{
    if (SCREEN_WIDTH > 375.0) {
        return [UIImage imageNamed:@"plus"];
    }
    else if (SCREEN_WIDTH > 320.0)
    {
        return [UIImage imageNamed:@"6"];
    }
    else
    {
       return  [UIImage imageNamed:@"5"];
    }
}

-(void)shareSDKIntegration
{
    [ShareSDK registerApp:@"6e4feb4bd7e076d02593134c38e8279d"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeMail),
                            @(SSDKPlatformTypeSMS),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeRenren),
                            ]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"2704196936"
                                           appSecret:@"1a70458bc3a0a52128fa99cef6550ae5"
                                         redirectUri:@"http://www.sharesdk.cn"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wxb54d373aab19aa23"
                                       appSecret:@"e4c170eb9cf4bfeb31cc1e25ef56de86"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1105657762"
                                      appKey:@"wpWUxqJJzeLcjVVg"
                                    authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeRenren:
                 [appInfo        SSDKSetupRenRenByAppId:@"226427"
                                                 appKey:@"fc5b8aed373c4c27a05b712acba0f8c3"
                                              secretKey:@"f29df781abdd4f49beca5a2194676ca4"
                                               authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];
}

-(void)launchAnimation
{
    self.bgImageView = [[UIImageView alloc] initWithImage:[self selectedImageByDevice]];
    
    [self.window addSubview:self.bgImageView];
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.window);
    }];
    
    UIImage *image = [UIImage imageNamed:@"logownezi"];
    self.splashView = [[UIImageView alloc] initWithImage:image];
    [self.bgImageView addSubview:self.splashView];
    
    [self.splashView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCALE*image.size.width);
        make.height.mas_equalTo(SCALE*image.size.height);
        make.centerX.equalTo(self.bgImageView);
        make.top.equalTo(self.bgImageView).offset(150*KHEIGHT_SCALE);
    }];
    
    
    self.splashView.alpha = 0.0;
    [UIView animateWithDuration:3 animations:^{
        
        self.splashView.alpha = 1.0;
        
    } completion:^(BOOL finished) {
        [self.bgImageView  removeFromSuperview];
        
        //版本更新
        if ([self.window.rootViewController isKindOfClass:[WPTabBarController class]])
        {
            WPTabBarController *tbc = (WPTabBarController *)self.window.rootViewController;
            WPHomeNavigationController *nvc = tbc.childViewControllers[0];
            WPHomeViewController *hvc = nvc.viewControllers[0];
            
            if (hvc.newVersionBlock)
            {
                hvc.newVersionBlock();
            }
            
            if (hvc.firstUsing)
            {
                hvc.firstUsing();
            }
        }
    }];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required -    DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    //  如果只支持iOS7以上的设备，在此处进行界面跳转
    // IOS 7 Support Required
    
    if(application.applicationState == UIApplicationStateActive)
    {
        //如果应用在前台,在这里执行
    }
    else
    {
        //        如果应用在后台,这里执行
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

/**
 如果证书配置出问题了，就会执行这个代理方法；只是用来调试的。
 
 @param application 应用
 @param error       错误
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
//    WPLog(@"***********did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    //    取消桌面右上角的红色标记
    [application setApplicationIconBadgeNumber:0];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary * userInfo = [notification userInfo];
    WPInfomationModel *model = [WPInfomationModel yy_modelWithDictionary:userInfo[@"extras"]];
    
    WPUserAccountViewModel *userAccountModel = [WPUserAccountViewModel sharedInstance];
    WPUserAccount *userAccount = userAccountModel.userAccount;
    
    if ([userInfo[@"extras"][@"type"] isEqualToString:@"personal"])
    {
        NSString *privateInfomationArr = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"privateInfomationArr_%zd.plist",userAccount.user.id]];
        
        NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:privateInfomationArr];
        if (!arr)
        {
            arr = [NSMutableArray array];
        }
        [arr addObject:model];
        
        if (arr.count >= 10)
        {
            [arr removeObjectAtIndex:0];
        }
        
        [NSKeyedArchiver archiveRootObject:arr toFile:privateInfomationArr];
        
//        有个人新消息
        [WPUserAccountViewModel sharedInstance].isNewPersonalInfo = YES;
        
        ////收到自定义消息时模拟系统弹窗
        BOOL isIOS10 = SYSTEM_VERSION_LESS_THAN(@"10.0");
        [EBForeNotification handleRemoteNotification:@{@"aps":@{@"alert":userInfo[@"extras"][@"content"]}} soundID:1312 isIos10:!isIOS10];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(eBBannerViewDidClick:) name:EBBannerViewDidClick object:nil];
        
        }
    else if ([userInfo[@"extras"][@"type"] isEqualToString:@"system"])
    {
        
    }
    
}

//点击模拟的系统弹窗的响应事件
-(void)eBBannerViewDidClick:(NSNotification*)noti
{
    WPMineInforamationVC *rVC = [WPMineInforamationVC new];
    rVC.isNotifactionDidClick = YES;
    WPMineInfomationNVC *pnc = [[WPMineInfomationNVC alloc] initWithRootViewController:rVC];
    [self.window.rootViewController presentViewController:pnc animated:YES completion:nil];
}

-(void)prepareKeyboardManager
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    
    manager.enable = YES;
    
    manager.shouldResignOnTouchOutside = YES;
    
    manager.enableAutoToolbar = YES;
//    [[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[WPRegisterViewController class]];
//    [manager disableToolbarInViewControllerClass:[WPReadingInvidialRanking class]];
//    [manager disableToolbarInViewControllerClass:[WPHomeNavigationController class]];
//    [manager disableDistanceHandlingInViewControllerClass:[WPReadingInvidialRanking class]];
}

@end
